from io import BytesIO
import logging
import random
from services.fipi import parse_questions_count, create_question_url, render_question
from aiogram.types import CallbackQuery, InputFile, CallbackQuery
from aiogram.dispatcher import FSMContext

from states.question import QuestionState


async def select_subject_callback_handler(callback_query: CallbackQuery, state: FSMContext):
    subject_id = callback_query.data.split(':')[1]

    questions_count = await parse_questions_count(subject_id)
    random_question_id = random.randint(1, questions_count)
    random_question_url = create_question_url(subject_id, random_question_id)

    async with state.proxy() as data:
        data["question_url"] = random_question_url

    await QuestionState.next()

    task_image = await render_question(random_question_url)

    photo = InputFile(BytesIO(task_image))

    caption = f"""
<a href="{random_question_url}">Ссылка на задание</a>
Введите ответ:
    """

    await callback_query.message.answer_photo(photo, caption, "html")
